<?php
class fwLoginGmail
{
	private static $service = null;
	private static $sourceCompany = null;
	private static $sourceApplication = null;
	private static $sourceVersion = null;

	private static $loaded = false;

	private static function initVars()
	{
		global $conf;

		if(self::$loaded)
		{
			return;
		}

		self::$service = $conf['login']['gmail']['service'];
		self::$sourceCompany = $conf['login']['gmail']['source_company'];
		self::$sourceApplication = $conf['login']['gmail']['source_application'];
		self::$sourceVersion = $conf['login']['gmail']['source_version'];

		self::$loaded = true;
	}

	public static function processLogin($datas)
	{
		self::initVars();

		$login  = $datas['login'];
		$password = urldecode($datas['password']);

		return self::processToken($login, $password);
	}

	private function processToken($login, $password)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,'https://www.google.com/accounts/ClientLogin');
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, 'accountType=HOSTED_OR_GOOGLE&Email='.$login.'&Passwd='.$password.'&service='.self::$service.'&source='.self::$sourceCompany.'-'.self::$sourceApplication.'-'.self::$sourceVersion);
		curl_setopt($ch, CURLOPT_HEADER, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		$header[] = "Content-type: application/x-www-form-urlencoded";
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

		$raw_response = curl_exec($ch);
		if(strpos($raw_response, 'HTTP/1.1 200 OK')===0)
		{
			return array(true, $login);
		}
		return array(false, '');
	}
}
?>